package main

import (
	"context"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	mdbopts "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	client, err := mgoClient()
	if err != nil {
		panic(err)
	}

	database := client.Database("test")
	userCol := database.Collection("user")
	rolCol := database.Collection("role")
	ctx := context.TODO()
	client.UseSession(ctx, func(sc mongo.SessionContext) error {
		sc.StartTransaction()
		defer sc.EndSession(sc)
		err = InsertUser(sc, userCol)
		if err != nil {
			return err
		}
		return InsertRole(sc, rolCol)
	})
}

func InsertUser(ctx context.Context, col *mongo.Collection) error {
	_, err := col.InsertOne(ctx, bson.M{"name": "zhansan3"})

	return err
}
func InsertRole(ctx context.Context, col *mongo.Collection) error {
	_, err := col.InsertOne(ctx, bson.M{"role": "admin3"})
	return err
}

func mgoClient() (*mongo.Client, error) {
	clientOptions := &mdbopts.ClientOptions{Hosts: []string{"127.0.0.1:27017"}}

	return mongo.Connect(context.TODO(), clientOptions)
}
